NOTE
1.8 TCP TIME_WAIT
Historical notes on TCP TIME_WAIT, why it exists, why it lasts 2MSL, and the high-concurrency short-connection problem.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is TIME_WAIT?
The side that actively closes a TCP connection enters the TIME_WAIT state after sending the final ACK.
2. Why Is TIME_WAIT Needed?
- To handle the case where the final ACK is lost and needs to be retransmitted.
- To prevent packets from an old connection that are still wandering around the network from being accepted by a new connection.
A connection is uniquely identified by the four-tuple (client IP, client port, server IP, server port). After a connection is closed and reopened, it should be a new connection, but the four-tuple cannot distinguish the new connection from the old one. This may cause packets left over from the previous connection to be treated as new packets after the new connection is opened, so packets from the old connection can “leak” into the new one, which is unacceptable.
3. Why Is TIME_WAIT Set to 2MSL?
Prerequisite: the time for a packet to travel from A to B is RTO, and RTO is shorter than MSL. For example, let the client be A and the server be B, and assume A actively closes the connection. Suppose A’s ACK packet is lost at the last moment of the RTO. At this point one RTO has passed (approximately treated as one MSL). B needs to retransmit the FIN packet, and it takes another RTO (approximately one MSL) for the FIN packet to reach A. Therefore, one RTO is used for the case where the ACK is lost at the last moment, and the other MSL is used for the retransmitted FIN.
4. Problems with TIME_WAIT
- Scenario A high-concurrency short-connection server actively closes connections. At this point a large number of connections enter TIME_WAIT and consume system resources, and new clients may be unable to connect.
- Cause
The network port range is 0-65535, and connections in TIME_WAIT still occupy ports.
The port range can be viewed with:
cat /proc/sys/net/ipv4/ip_local_port_range - Solution
Enable TIME_WAIT reuse and fast recycling through two kernel parameters in
sysctl:net.ipv4.tcp_tw_reuse = 1 // enable reuse; allows TIME-WAIT sockets to be reused for new TCP connections. Default is 0. net.ipv4.tcp_tw_recycle = 1 // enable fast recycling of TIME-WAIT sockets. Default is 0.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub